import { Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';

import { Order } from '../entity/order.entity';

@Provide()
export class OrderService {
    @InjectEntityModel(Order)
    orderModel: Repository<Order>;

    /**
     * 创建订单
     */
    async create(order: Partial<Order>): Promise<Order> {
        // 生成唯一订单编号
        if (!order.orderNo) {
            order.orderNo = this.generateOrderNo();
        }

        const newOrder = this.orderModel.create(order);
        return await this.orderModel.save(newOrder);
    }

    /**
     * 更新订单
     */
    async update(id: number, order: Partial<Order>): Promise<boolean> {
        const result = await this.orderModel.update(id, order);
        return result.affected > 0;
    }

    /**
     * 删除订单（软删除）
     */
    async delete(id: number): Promise<boolean> {
        const result = await this.orderModel.update(id, {
            delFlag: 1,
            updateTime: new Date()
        });
        return result.affected > 0;
    }

    /**
     * 获取订单信息
     */
    async getInfo(id: number): Promise<Order> {
        return await this.orderModel.findOne({
            where: { id, delFlag: 0 }
        });
    }

    /**
     * 获取订单列表
     */
    async getList(params: {
        page?: number;
        pageSize?: number;
        orderNo?: string;
        userId?: number;
        status?: number;
    }): Promise<[Order[], number]> {
        const { page = 1, pageSize = 10, orderNo, userId, status } = params;

        const queryBuilder = this.orderModel.createQueryBuilder('order')
            .where('order.delFlag = :delFlag', { delFlag: 0 });

        if (orderNo) {
            queryBuilder.andWhere('order.orderNo LIKE :orderNo', {
                orderNo: `%${orderNo}%`
            });
        }

        if (userId) {
            queryBuilder.andWhere('order.userId = :userId', { userId });
        }

        if (status !== undefined) {
            queryBuilder.andWhere('order.status = :status', { status });
        }

        return await queryBuilder
            .orderBy('order.createTime', 'DESC')
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
    }

    /**
     * 生成订单编号
     */
    private generateOrderNo(): string {
        const now = new Date();
        const year = now.getFullYear().toString();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
        return `ORD${year}${month}${day}${random}`;
    }
}